package com.googlecode.strutson.commands

import com.googlecode.strutson.utils.ConsoleUtils
import com.googlecode.strutson.utils.EnvVariables
import com.googlecode.strutson.utils.TemplateUtils
import org.apache.commons.io.FileUtils
import org.apache.commons.lang.StringUtils

/**
 * Creates a new entity in the "models" directory
 */
class CreateModel {
    String className;

    void run() {
        className = StringUtils.capitalize(readClassName())
        File modelSrc = new File("${EnvVariables.HOME}/templates/src/models/model.java")
        def modelTrg = new File("${EnvVariables.MODELS_DIR}/${className}.java")
        FileUtils.copyFile(modelSrc, modelTrg);

        //expand template
        TemplateUtils.processAndSave(modelTrg, [
                'className': className,
                'rootPackage': EnvVariables.ROOT_PACKAGE
        ])

        println "Generated model ${modelTrg}"
    }

    String readClassName() {
        def appName = ConsoleUtils.readLine('Enter the class name(without package, or extension): ', {String text ->
            def message = 'Please enter a valid class name'
            boolean valid = true;
            if ((valid = StringUtils.isNotBlank(text))) {
                valid = Character.isJavaIdentifierStart((char) text[0])
                if (valid) {
                    text.substring(1).each {
                        valid = Character.isJavaIdentifierPart((char) it);
                        if (!valid)
                            return;
                    }
                }
            }

            if (!valid) {
                println message
                return false;
            } else
                return true;
        })

        assert StringUtils.isAlphanumeric(appName);
        return appName;
    }
}
